# coding:utf-8
from io import BytesIO
import requests
import dlib
import numpy as np 
from PIL import Image

class FaceDetector():
    def __init__(self, predictor_path, face_rec_model_path):
        self.detector = dlib.get_frontal_face_detector()
        self.sp = dlib.shape_predictor(predictor_path)
        self.facerec = dlib.face_recognition_model_v1(face_rec_model_path)

    def detect(self, img):
        dets = self.detector(img, 1)
        results = []
        for k, d in enumerate(dets):
            shape = self.sp(img, d)
            face_chip = dlib.get_face_chip(img, shape)        
            face_descriptor_from_prealigned_image = self.facerec.compute_face_descriptor(face_chip)
            results.append({
                "rect":{
                    "x1": d.left(),
                    "y1": d.top(),
                    "x2": d.right(),
                    "y2": d.bottom()
                },
                "features": list(face_descriptor_from_prealigned_image)
            })
        return results

    def detect_by_url(self, img_url):
        res = requests.get(img_url)
        if res.status_code == 200 and 'jpeg' in res.headers['content-type']:
            img_arr = np.array(Image.open(BytesIO(res.content)))
            return self.detect(img_arr)
        else: 
            # print('url:{}, status:{}'.format(img_url, res.status_code))
            return []